<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\facade\Filesystem;
use think\facade\Cookie;

class User extends Controller
{
    protected $middleware = ['Auth'];

    public function add(){
        $post = input('post.');
        try{
            if(Db::name('user')->insert($post))
                return json(['code'=>200,'msg'=>'添加成功']);
            return json(['code'=>-1,'msg'=>'添加失败']);
        } catch (\Exception $e) {
            if ($e->getData()["PDO Error Info"]["Driver Error Code"] == 1062)
                return json(["code"=>-1,"msg"=>"该账号已存在"]);
            throw $e;
        };
    }

    public function edit(){
        $post = input('post.');
        if($post['password'] == '')
            unset($post['password']);
        $id = $post['id'];
        unset($post['id']);
        if(Db::name('user')->where(['id'=>$id])->update($post))
            return json(['code'=>200,'msg'=>'修改成功']);
        return json(['code'=>-1,'msg'=>'修改失败']);
    }

    public function delete(){
        $post = input('post.');
        if(Db::name('user')->where(['id'=>$post['id']])->delete())
            return json(['code'=>200,'msg'=>'删除成功']);
        return json(['code'=>-1,'msg'=>'删除失败']);
    }

    public function logOut(){
        Cookie::delete('token');
        return json(['code'=>200,'msg'=>'推出成功']);
    }

    public function setUserPassword(){
        $post = input('post.');
        if(!input('?post.oldPassword') || !input('?post.newPassword'))
            return json(['code'=>-1,'msg'=>'信息不完整','data'=>[]]);
        if(!Db::name('user')->where('id',$this->request->userInfo['id'])->where('password',$post['oldPassword'])->find())
            return json(['code'=>-1,'msg'=>'旧密码不正确','data'=>[]]);
        if(Db::name('user')->where('id',$this->request->userInfo['id'])->update(['password'=>$post['newPassword']])){
            return json(['code'=>200,'msg'=>'修改成功','data'=>[]]);
        }else{
            return json(['code'=>-1,'msg'=>'修改失败','data'=>[]]);
        }
    }
}